import { combineReducers } from "redux";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";
import { applyMiddleware, compose } from "redux";
import thunkMiddleware from "redux-thunk";
import promiseMiddleware from "redux-promise";
import createSagaMiddleware from 'redux-saga';
import { configureStore } from '@reduxjs/toolkit';

// Import reducers
import global from "./modules/global/reducer";
import menu from "./modules/menu/reducer";
import tabs from "./modules/tabs/reducer";
import auth from "./modules/auth/reducer";
import breadcrumb from "./modules/breadcrumb/reducer";
import app from "./reducers/app";
import dataCenter from "./reducers/dataCenter";
import patrolCenter from "./reducers/patrolCenter";
import loading from "./reducers/loading";

// Import root saga
import rootSaga from './sagas/index';

// Combine reducers
const reducer = combineReducers({
	global,
	menu,
	tabs,
	auth,
	breadcrumb,
	app,
	dataCenter,
	patrolCenter,
	loading,
});

// Redux Persist configuration
const persistConfig = {
	key: "redux-state",
	storage: storage,
};

// Persisted reducer
const persistedReducer = persistReducer(persistConfig, reducer);

// Create saga middleware
const sagaMiddleware = createSagaMiddleware();

// Middlewares
const middleWares = [thunkMiddleware, promiseMiddleware, sagaMiddleware];

// Configure store with Redux Toolkit
const store = configureStore({
	reducer: persistedReducer,
	middleware: (getDefaultMiddleware) =>
		getDefaultMiddleware({
			serializableCheck: false,
		}).concat(middleWares),
	enhancers: [compose],
});

// Run root saga
sagaMiddleware.run(rootSaga);

// Create persistor
const persistor = persistStore(store);

// Export types
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;

// Export store and persistor
export { store, persistor };
